<?php
declare(strict_types=1);

namespace Service\MemberService;

use App\Model\BbcModel\ConfigChannel;
use App\Model\BbcModel\Mnuser;
use App\Model\BbcModel\StoreConfig;
use App\Model\BbcModel\VipLog;
use App\Model\BbcModel\VipLogExtends;
use Service\BaseService;
use Service\ConfigureService\ChannelConfigService;
use Service\MemberService\Volidate\MemberVolidate;
use Service\UserService\MnUserService;
use App\Model\BbcModel\Member;
use App\Model\BbcModel\Vip;
use App\Model\BbcModel\MemberInfo;
use Service\Code\Normal;
use App\Model\BbcModel\Address;
use Service\Code\Billcode;
use Service\AuthService\IdCardAuthService;
use Service\HelperService\StringService;
use Service\AddressService\AddressService;
use Service\MnBudgetService\MnBudgetService;
use Service\PayService\CashPayService;
use App\Model\BbcModel\Order;
use App\Model\BbcModel\CashRegister;

class MemberService extends BaseService
{
    /**
     * 获取会员列表
     * @param int $cid
     * @param int $mn_sid
     * @param array $body
     */
    public function getMembers(int $cid,int $mn_sid,array $body = [])
    {
        $page  = $body['page']??1;
        $limit = $body['limit']??10;
        
        $query = Member::instance()->where('df',0);
        
        //查询店铺
        $mn_user  = MnUserService::getMnUserInfoByMnSid((int)$mn_sid);
        if( $mn_user['member_share'] == 1 ) {
            $list = Mnuser::instance()->lists(['member_share'=>1,'pid'=>$mn_user['pid'],'status'=>1,'new_store'=>1,'_fields_'=>'id']);
            $mn_share_ids = array_column($list,'id');
            if( $mn_share_ids ) {
                $query->whereIn('mn_sid',$mn_share_ids);
            }
        } else{
            $mn_share_ids = [$mn_sid];
            $query->where('mn_sid',$mn_sid);
        }
        
        if( !empty($body['account']) ) {
            $query->where('account','like',"%{$body['account']}%");
        }
        
        if ( !empty($body['starttime']) ) {
            $query->where('cd','>=',strtotime($body['starttime']));
        }
        if ( !empty($body['endtime']) ) {
            $query->where('cd','<=',strtotime($body['endtime']));
        }
        
        if( !empty($body['type']) ) 
        {
            //会员用户
            $vip_list = Vip::instance()->select(['mid'])->where('expire_time','>',time())->whereIn('mn_sid',$mn_share_ids)->get()->toArray();
            if(!empty($vip_list)){
                $mids = array_unique(array_column($vip_list,'mid'));
                if( $body['type'] == 1 ) {
                    //全是普通用户
                    $query->whereNotIn('mid',$mids);
                } else {
                    //会员用户
                    $query->whereIn('mid',$mids);
                }
            }else{
                if( $body['type'] == 2 ){
                    //没有会员用户，全是普通用户
                    $query->where('mid',0);
                }
            }
        }
        
        $select = [
            'mid',
            'account',
            'cd',
            'points',
            'vip_level',
            'vip_expired',
            'vip_type',
            'goods_points'
        ];
        $pageInfo = $query->paginate((int)$limit,$select, 'page', (int)$page,true)->toArray();
        $list = $pageInfo['data'];
        
        $mids = array_column($list,'mid');
        $memberList = $this->getMemberInfoListByMids($mids);
        $memberListMap = array_column($memberList,null,'mid');
        
//        $checkUserIsBlackVipCards = VipService::instance()->checkUserIsBlackVipCard($mn_user,$mids);
//        $checkUserIsBlackVipCardsMap = array_column($checkUserIsBlackVipCards,null,'mid');        
        foreach ($list as & $info)
        {
            $mid = $info['mid'];
            $info['nickname']   = isset($memberListMap[$mid]) ? $memberListMap[$mid]['nickname']:'';
            $info['truename']   = isset($memberListMap[$mid]) ? $memberListMap[$mid]['truename']:'';
            $info['sex']        = isset($memberListMap[$mid]) ? $memberListMap[$mid]['sex'] : '';
            $info['birthday']   = isset($memberListMap[$mid]) ? $memberListMap[$mid]['birthday'] : '';
            
            //如果黑卡用户
//            if( $checkUserIsBlackVipCardsMap[$mid]['is_vip'] == 1 ) {
//                $info['is_vip']         = 2;
//                $info['type']           = "黑卡会员";
//                $info['expire_time']    = date('Y-m-d',$checkUserIsBlackVipCardsMap[$mid]['expire_time']);
//            }else{
//                $info['is_vip']         = 1;
//                $info['type']           = "普通会员";
//                $info['expire_time']    = '-';
//            }
            if($info['vip_level']==1 && $info['vip_expired']>time()){
                $info['is_vip']=2;
                $info['type']="黑卡会员";
                $info['expire_time']=date('Y-m-d',$info['vip_expired']);
            }elseif($info['vip_level']==2 && $info['vip_expired']>time()){
                $info['is_vip']=2;
                $info['type']="高级会员";
                $info['expire_time']=date('Y-m-d',$info['vip_expired']);
            }else{
                $info['is_vip']=1;
                $info['type']="普通会员";
                $info['expire_time']='-';
            }
        }
        return Normal::returnCode(Normal::SUC, '成功', [
            'list'          => $list,
            'totalcount'    => $pageInfo['total']
        ]);
    }
        
    /**
     * 获取会员信息列表
     * @param array $mids
     */
    public function getMemberInfoListByMids( array $mids = [] )
    {
        if( empty($mids) ) {
            return [];
        }
        return MemberInfo::instance()->whereIn('mid',$mids)->get()->toArray();
    }
    
    /**
     * 获取会员信息
     * @param int $mid
     */
    public function getMemberByMid( int $mid )
    {
        return Member::instance()->info(['mid'=>$mid]);
    }
    
    /**
     * 获取会员信息
     * @param int $mid
     */
    public function getMemberInfoByMid( int $mid )
    {
        return MemberInfo::instance()->info(['mid'=>$mid]);
    }
    
    /**
     * 获取会员详情
     * @param string $account
     * @return mixed
     */
    public function getMemberInfo(int $cid,int $mn_sid,array $body = [])
    {
        if( empty($body['account']) ) {
            return Normal::returnCode(Normal::FAIL, '参数账号不能为空');
        }
        $select = [
            'mid',
            'account',
            'cd',
            'points',
            'vip_level',
            'vip_expired',
            'vip_type',
            'goods_points'
        ];
        $query = Member::instance()->select($select)->where('df',0);
        //查询店铺
        $mn_user = MnUserService::getMnUserInfoByMnSid((int)$mn_sid);
        if( $mn_user['member_share'] == 1 ) {
            $list = Mnuser::instance()->lists(['member_share'=>1,'pid'=>$mn_user['pid'],'status'=>1,'new_store'=>1,'_fields_'=>'id']);
            $mn_share_ids = array_column($list,'id');
            if( $mn_share_ids ) {
                $query->whereIn('mn_sid',$mn_share_ids);
            }
        } else{
            $query->where('mn_sid',$mn_sid);
        }
        
        if( !empty($body['account']) ) {
            $query->where('account',$body['account']);
        }
        
        $info = $query->first();
        if(empty($info)){
            return Normal::returnCode(Normal::FAIL,'未查询到会员信息');
        }
        $info = $info->toArray();
        $mid = $info['mid'];



        $memberinfo = MemberService::instance()->getMemberInfoByMid($mid);
        $info['nickname']   = $memberinfo['nickname'];
        $info['truename']   = $memberinfo['truename'];
        $info['idcard']     = $memberinfo['idcard'];
        $info['mobile']     = $memberinfo['mobile'];
        $info['sex']        = $memberinfo['sex'];
        $info['birthday']   = $memberinfo['birthday'];
        $info['avatar']     = $memberinfo['avatar']??'';

        //处理黑卡问题
//        $checkUserIsBlackVipCards   = VipService::instance()->checkUserIsBlackVipCard($mn_user,[$mid]);
//        $checkUserIsBlackVipCardsMap = array_column($checkUserIsBlackVipCards,null,'mid');
//        if( $checkUserIsBlackVipCardsMap[$mid]['is_vip'] == 1 ) {
//            $info['is_vip']         = 2;
//            $info['type']           = "黑卡会员";
//            $info['expire_time']    = date('Y-m-d',$checkUserIsBlackVipCardsMap[$mid]['expire_time']);
//        }else{
//            $info['is_vip']         = 1;
//            $info['type']           = "普通会员";
//            $info['expire_time']    = '-';
//        }
        
        if($info['vip_level']==1 && $info['vip_expired']>time()){
            $info['is_vip']     =2;
            $info['type']       ="黑卡会员";
            $info['expire_time']=date('Y-m-d',$info['vip_expired']);
        }elseif($info['vip_level']==2 && $info['vip_expired']>time()){
            $info['is_vip']     =2;
            $info['type']       ="高级会员";
            $info['expire_time']=date('Y-m-d',$info['vip_expired']);
        }else{
            $info['is_vip']     =1;
            $info['type']       ="普通会员";
            $info['expire_time']='-';
        }
        
        if($mn_user['is_autovip']==1){
            if($info['is_vip']==1){
                VipService::instance()->addVipByCashAuto($info['mid'], $mn_sid);
                $info['is_vip']=2;
                $info['type']="黑卡会员";
                $info['expire_time']=strtotime(date('Y-m-d',time()))+(366)*86400;
            }
        }
        
/*        $addres = Address::instance()->info(['mid'=>$mid,'is_default'=>1]);
        if($addres){
            $addres['buyer']    = [
                'truename' => $addres['true_name'] ?? '',
                'idcard'   => $addres['idcard'] ?? '',
                'mobile'   => $addres['mobile'] ?? ''
            ];
            $addres['province'] = ['id' => $addres['province']];
            $addres['city']     = ['id' => $addres['city']];
            $addres['area']     = ['id' => $addres['area']];
            $addres['address']  = $addres['address'];
        }*/
        $order= Order::instance()->info([
            'cid'           => $cid,
            'mn_sid'        => $mn_sid,
            'mid'  => $info['mid'],
            '_order_'       =>['cd'=>'desc']
        ]);
        if(!empty($order['receive_info'])){ //最后一个下单地址
            $addres=json_decode($order['receive_info'],true);

        }else{
            $addres = Address::instance()->info(['mid'=>$mid,'is_default'=>1]);
            if($addres){ //收货地址
                $addres['buyer']    = [
                    'truename' => $addres['true_name'] ?? '',
                    'idcard'   => $addres['idcard'] ?? '',
                    'mobile'   => $addres['mobile'] ?? ''
                ];
                $addres['province'] = ['id' => $addres['province']];
                $addres['city']     = ['id' => $addres['city']];
                $addres['area']     = ['id' => $addres['area']];
                $addres['address']  = $addres['address'];
            }else if($memberinfo['province'] && $memberinfo['city'] && $memberinfo['area'] && $memberinfo['address']){ //个人资料地址
                $addres['buyer']    = [
                    'truename' => $memberinfo['truename'] ?? '',
                    'idcard'   => $memberinfo['idcard'] ?? '',
                    'mobile'   => $memberinfo['mobile'] ?? ''
                ];
                $addres['province'] = ['id' => $memberinfo['province']];
                $addres['city']     = ['id' => $memberinfo['city']];
                $addres['area']     = ['id' => $memberinfo['area']];
                $addres['address']  = $memberinfo['address'];
            }else{
                $addres = null;
            }
        }
        /*if(empty($order['receive_info'])){
           // $addres = Address::instance()->info(['mid'=>$mid,'is_default'=>1]);
            if($memberinfo['is_full']==1){
                $addres['buyer']=[
                    'truename'=>$memberinfo['truename']??'',
                    'idcard'=>$memberinfo['idcard']??'',
                    'mobile'=>$memberinfo['mobile']??''
                ];
                $addres['province']=['id'=>$memberinfo['province']];
                $addres['city']=['id'=>$memberinfo['city']];
                $addres['area']=['id'=>$memberinfo['area']];
                $addres['address']=$memberinfo['address'];
            }else{
                $addres=NULL;
            }
        }else{
            $addres=json_decode($order['receive_info'],true);
        }*/
        $info['address']= $addres;
        $info['store_self_address']=$memberinfo['store_self_address']?json_decode($memberinfo['store_self_address'],true):[];
        $info['store_express_address']=$memberinfo['store_express_address']?json_decode($memberinfo['store_express_address'],true):[];
        return Normal::returnCode(Normal::SUC,'成功',$info);
    }
    
    /**
     * 用户会员累计消费更新
     * @param int $mid
     * @param string $money
     * @param int $time
     * @return mixed
     */
    public function memberOrderMoneyConsume(int $mid,string $money,int $time)
    {
        //累计消费
        $memberconsumeres= Member::instance()->where(['mid'=>$mid])->increment('consume',$money);
        if(!$memberconsumeres){
            return Normal::returnCode(Normal::FAIL, '更新累计消费失败');
        }
        
        //更新最后购买时间
        $memberLastPay = Member::instance()->edit(['mid'=>$mid], ['pay_time'=>$time]);
        if(!$memberLastPay){
            return Normal::returnCode(Normal::FAIL, '更新最后购买时间失败');
        }
        return Normal::returnCode(Normal::SUC, '操作完成');
    }

    /**
     * 新增会员和收货地址
     * @param array $param
     * @return array
     */
    public function addma( array $param)
    {
        $mnuser= Mnuser::instance()->info(['id'=>$param['mn_sid']]);
        if($mnuser['member_share']==2){
            $where = [
                'account' => $param['mobile'],
                'mn_sid' => $param['mn_sid']??0,
                'cid' => $param['cid'],
            ];
        }else{
            $mnusers = Mnuser::instance()->lists(['pid'=>$param['cid'],'member_share'=>1]);
            $ids= array_column($mnusers, 'id');
            $where = [
                ['account' ,'=', $param['mobile']],
                ['mn_sid' ,'in', $ids],
                ['cid' ,'=', $param['cid']],
            ];
        }
        $member= Member::instance()->info($where);
        if (!empty($member)) {
            return Normal::returnCode(Normal::FAIL, '账号已经存在');
        }
        Member::instance()->startTrans();
        try{
            $account = $this->createAccount(['cid'=>$param['cid'],'mn_sid'=>$param['mn_sid'],'account'=>$param['mobile'],'password'=>$param['mobile'],'client'=>'cash']);
            if($account['code']!= Normal::SUC){
                throw new \Exception($account['msg']);
            }
            $accountres = Member::instance()->edit(['mid'=>$account['data']], ['edit_manager'=>$param['manager_name'],'edit_time'=>time()]);
            if(!$accountres){
                throw new \Exception('失败,会员');
            }
            $addressdata = [
                'mid'        => $account['data'],
                'true_name'  => $param['true_name'],
                'idcard'     => $param['idcard'],
                'mobile'     => $param['mobile'],
                'province'   => $param['province'],
                'city'       => $param['city'],
                'area'       => $param['area'],
                'address'    => $param['address'],
                'is_default' => 1,
                'cid'        => $param['cid']
            ];
            $address = AddressService::instance()->newAddress($addressdata);
            if($address['code'] != Normal::SUC){
                throw new \Exception($address['msg']);
            }
            $data = $this->getMemberInfo($param['cid'],$param['mn_sid']);
            Member::instance()->commit();
            return Normal::returnCode(Normal::SUC, '操作成功',$data['data']);
        }catch (\Exception $e){
            Member::instance()->rollback();
            return Normal::returnCode(Normal::FAIL,$e->getMessage());
        }

        return Normal::returnCode(Normal::SUC,'请求成功');
    }

    /**
     * 开通会员新版
     * @param int $cid
     * @param int $mn_sid
     * @param string $manager_name
     * @param int $manager_id
     * @param int $casher_id
     * @param array $body
     * @return array
     */
    public function registerMemberNew(int $cid,int $mn_sid,string $manager_name,int $manager_id,int $casher_id,array $body = [])
    {
        $checkResult = MemberVolidate::instance()->checkRegisterMemberParam($cid,$mn_sid,$body);
        if ($checkResult['code'] != Normal::SUC){
            return $checkResult;
        }
        $cash_register= CashRegister::instance()->info(['id'=>$casher_id]);
        if(empty($cash_register)){
            return Normal::returnCode(Normal::FAIL,"未找到收银台");
        }
        $body   = $checkResult['data'];
//        $config = ChannelConfigService::instance()->getConfig(['cid'=>$casher_id,'code'=>'member_vip_fee']);
//        if(isset($config['data']['value']['day'])){
//            $day = $config['data']['value']['day'] ;
//        }else{
            $day = MemberVolidate::DEFATUL_FREE_DAY;
        //}
        //订单号
        $sn = $body['sn'] ?? Billcode::returnCode('', $mn_sid);
        $time = time();

        $vipOrder=[
            'mid'       => '',
            'mn_sid'    => $mn_sid,
            'sn'        => $sn,
            'type'      => 2,
            'amount'    => $body['money']??0,
            'days'      => $day,
            'cd'        => $time,
            'pay_time'  => $time,
            'pay_status'=> 1
        ];

        $vip=[
            'mid'         => '',
            'mn_sid'      => $mn_sid,
            'start_time'  => $time,
            'cd'          => $time,
            'type'        => 1,
            'expire_time' => strtotime(date('Y-m-d',$time))+($day+1)*86400
        ];

        $mnuser    = Mnuser::instance()->info(['id'=>$mn_sid]);

        //判断是否是前置仓的店铺
//        if ($mnuser['type'] == Mnuser::TYPE_STORE_QZ){
//            $storeConfig = StoreConfig::instance()->getConfig(['mn_sid'=>$mn_sid,'code'=>'pay_way']);
//        }else{
//            $storeConfig = ConfigChannel::instance()->getConfig(['cid'=>$cid,'code'=>'pay_way']);
//        }
        $storeConfig = StoreConfig::instance()->getConfig(['mn_sid'=>$mn_sid,'code'=>'pay_way']);
        $scan_rece_type = $storeConfig['data']['value']['type'] ?? 0;

//        //判断是否扫码支付
//        if(isset($body['scan_code'])){
//            if(in_array(9, $body['pay_way'])){
//                $scan_rece_type=0;
//            }elseif(in_array(10, $body['pay_way'])){
//                $scan_rece_type=3;
//            }}
        $pay_fee = ConfigChannel::instance()->getPayFee(['cid' => $cid]);
        $vipOrder['pay_rate']=$pay_fee;
        $extendsData = [
            'cd'                => $time,
            'cid'               => $cid,
            'mn_sid'            => $mn_sid,
            'giveup_money'      => $body['giveup_money'] ?? 0,
            'pay_way'           => isset($body['pay_way'])?implode(',', $body['pay_way']):0,
            'cash'              => $body['cash'] ?? 0,
            'scan_pay'          => $body['scan_pay'] ?? 0,
            'scan_rece'         => $body['scan_rece'] ?? 0,
            'scan_rece_type'    => $scan_rece_type,
            'pos'               => $body['pos'] ?? 0,
            'storecard'         => $body['storecard'] ?? 0,
            'storecard_id'      => $body['storecard_id'] ?? 0,
            'balance'           => $body['balance'] ?? 0,
            'coupon'            => $body['coupon'] ?? 0,
            'points'            => $body['points'] ?? 0,
            'cashregister_id'   => $casher_id,
            'casher'            => $manager_id
        ];
        Member::instance()->startTrans();
        try {
            if ($body['vip'] == 1){
                if ($body['is_pay'] ==1){
                    if(isset($body['scan_rece'])&&$body['scan_rece']>0){
                        $extra=[
                            'auth_code'=>$body['scan_code'],
                            'out_trade_no'=>$sn,
                            'body'=>'门店付款',
                            'total_fee'=>$body['scan_rece'],
                            'cid'=>$cid,
                            'mn_sid'=>$mn_sid,
                            'store_type'=>$mnuser['type'],
                            'buyer'=>$body['buyer']??[],
                            'order_id'=>'',
                            'scan_rece_type'=>$scan_rece_type,
                            'is_order'=>0,
                            'cash_register'     => $cash_register
                        ];
                        $user_pay_result = CashPayService::instance()->userPay($cid, $mn_sid,4, $extra);
                        if($user_pay_result['code'] == 200){
                            $vipOrder['pay_serial']=$user_pay_result['data']['transaction_id'];
                            $vipOrder['pay_time']=$time;
                            $vipOrder['is_online']=1;
                            $vip['type']=0;
//                            if($mnuser['type']==Mnuser::TYPE_STORE_QZ){
//                                $distribute_money=0;
//                                $vipOrder['is_online']=0;
//                            }else{
//                                $distribute_money=bcmul($body['scan_rece'], $pay_fee,2);
//                            }
                            //店铺收款不分佣
//                            if($mnuser['type']!=Mnuser::TYPE_STORE_QZ){
//                                $budgete_extra=[
//                                    'type'       => MnBudgetService::TYPE_EXPENDITURE,
//                                    'money_type' => MnBudgetService::MONEY_TYPE_MEMBER,
//                                    'pay_type'   => 8,
//                                    'pay_serial' => $vipOrder['pay_serial'],
//                                    'sn'         => $sn,
//                                    'goods_id'   => 0,
//                                    'channel_money'      => $body['scan_rece'],
//                                    'channel_amount'     => 0,
//                                    'store_money'      => $distribute_money,
//                                    'store_amount'     => bcadd((string)$distribute_money, (string)$mnuser['wallet_income'], 2),
//                                    'remark'     => '购买会员卡收入',
//                                    'distribute_money'=>$distribute_money
//                                ];
//                                $mnbudget= MnBudgetService::instance()->addBudget($cid, $mn_sid, $mnuser['mid'], 4, $budgete_extra);
//                                if($mnbudget['code']!= Normal::SUC){
//                                    Member::instance()->rollback();
//                                    return $mnbudget;
//                                }
//                            }
                        }else{
                            Member::instance()->rollback();
                            return $user_pay_result;
                        }
                    }else{
                        $vipOrder['pay_serial']=Billcode::returnCode('', $mn_sid);
                        $vipOrder['pay_time']=$time;
                        $vipOrder['is_online']=1;
                        $vip['type']=0;
                    }
                } else {
                    $vipOrder ['type']=3;
                    $vipOrder ['is_online']=1;
                    $vip      ['type']=1;
                }
            }
            $account=$this->createAccount(['cid'=>$cid,'mn_sid'=>$mn_sid,'account'=>$body['account'],'password'=>$body['account'],'client'=>'cash']);
            if($account['code']!= Normal::SUC){
                Member::instance()->rollback();
                return Normal::returnCode(Normal::FAIL, $account['msg']);
            }
            $vipOrder['mid']=$account['data'];
            $vip['mid']=$account['data'];
            $accountres=Member::instance()->edit(['mid'=>$account['data']], ['edit_manager'=>$manager_name,'edit_time'=>$time]);
            if(!$accountres){
                Member::instance()->rollback();
                return Normal::returnCode(Normal::FAIL, '失败,会员');
            }
            $info_data  = [
                'nickname' => !empty($body['nickname']) ? $body['nickname'] : '',
                'sex'      => !empty($body['sex']) ? $body['sex'] : '',
                'birthday' => !empty($body['birthday']) ? $body['birthday'] : '',
            ];
            $memberinfo= MemberInfo::instance()->edit(['mid' => $account['data']], $info_data);
            if(!$memberinfo){
                Member::instance()->rollback();
                return Normal::returnCode(Normal::FAIL, '失败,会员扩展资料');
            }
            if($body['vip']==1){
                $viplog=VipLog::instance()->add($vipOrder);    
                if(!$viplog){
                    Member::instance()->rollback();
                    return Normal::returnCode(Normal::FAIL, '失败,会员订单');
                }
                $extendsdata['vip_log_id']=$viplog;
                $orderextendsres= VipLogExtends::instance()->add($extendsdata);
                if(!$orderextendsres){
                    Member::instance()->rollback();
                    return Normal::returnCode(Normal::FAIL, '订单扩展新增失败');
                }
                $vipres=Vip::instance()->add($vip);
                if(!$vipres){
                    Member::instance()->rollback();
                    return Normal::returnCode(Normal::FAIL, '失败,会员记录');
                }
                $membereditres=Member::instance()->edit(['mid'=>$account['data']],['vip_type'=>$vip['type'],'vip_level'=>1,'vip_expired'=>$vip['expire_time']]);
                if(!$membereditres){
                    Member::instance()->rollback();
                    return Normal::returnCode(Normal::FAIL, '失败,会员更新');
                }
            }
            Member::instance()->commit();
        }catch (\Exception $e){
            Member::instance()->rollback();
            return Normal::returnCode(Normal::FAIL, $e->getMessage());
        }


        return Normal::returnCode(Normal::SUC, '操作成功');
    }



   
    

    /**
     * 开通会员
     * @param int $cid
     * @param int $mn_sid
     * @param string $manager_name
     * @param array $body
     * @return array
     */
    public function registerMember(int $mn_sid,int $cid,string $manager_name,array $body = []):array
    {

        $account = $body['account'] ?? '';
        $res = $this->createAccount([
            'cid'      => $cid,
            'mn_sid'   => $mn_sid,
            'account'  => $account,
            'password' => $account, //原逻辑密码和账号一致
            'client'   => 'cash'    //收银机接口
            ]
        );

        if ($res['code'] != Normal::SUC){
            return $res;
        }

        Member::instance()->edit([
            'mid' => $res['data'],
            'edit_manager' => $manager_name,
            'edit_time' => time()
        ]);

        return Normal::returnCode(Normal::SUC,'成功');
    }

    /**
     * 升级/续费会员
     * @param int $cid
     * @param int $mn_sid
     * @param string $manager_name
     * @param int $cashregister_id
     * @param int $manager_id
     * @param array $body
     * @return array
     */
    public function memberLevelUp(int $cid, int $mn_sid, string $manager_name, int $cashregister_id, int $manager_id, array $body = [])
    {
        $body['vip']=1;
        $checkResult = MemberVolidate::instance()->checkRegisterMemberParam($cid,$mn_sid,$body,0);
        if ($checkResult['code'] != Normal::SUC){
            return $checkResult;
        }
        $cash_register= CashRegister::instance()->info(['id'=>$cashregister_id]);
        if(empty($cash_register)){
            return Normal::returnCode(Normal::FAIL,"未找到收银台");
        }
        $body   = $checkResult['data'];
//        $config = ChannelConfigService::instance()->getConfig(['cid'=>$cashregister_id,'code'=>'member_vip_fee']);
//        if(isset($config['data']['value']['day'])){
//            $day = $config['data']['value']['day'] ;
//        }else{
            $day = MemberVolidate::DEFATUL_FREE_DAY;
//        }
        $sn=isset($body['sn'])?$body['sn']:Billcode::returnCode('V', $mn_sid);
        $time=time();
        $mid=$body['mid'];
        $vipOrder=[
            'mn_sid'=>$mn_sid,
            'sn'=>$sn,
            'type'=>2,
            'amount'=>$body['money'],
            'days'=> $day,
            'cd'=>$time,
            'pay_time'=>$time,
            'pay_status'=>1,
            'mid'=>$mid
        ];
        $vip=[
            'mid'=>$mid,
            'mn_sid'=>$mn_sid,
            'start_time'=>$time,
            'cd'=>$time,
            'type'=>1,
            'expire_time'=>strtotime(date('Y-m-d',$time))+($day+1)*86400
        ];
        $mnuser    = Mnuser::instance()->info(['id'=>$mn_sid]);

        //判断是否是前置仓的店铺
//        if ($mnuser['type'] == Mnuser::TYPE_STORE_QZ){
//            $storeConfig = StoreConfig::instance()->getConfig(['mn_sid'=>$mn_sid,'code'=>'pay_way']);
//        }else{
//            $storeConfig = ConfigChannel::instance()->getConfig(['cid'=>$cid,'code'=>'pay_way']);
//        }
        $storeConfig = StoreConfig::instance()->getConfig(['mn_sid'=>$mn_sid,'code'=>'pay_way']);
        $scan_rece_type = $storeConfig['data']['value']['type'] ?? 0;

        //判断是否扫码支付
//        if(isset($body['scan_code'])){
//            if(in_array(9, $body['pay_way'])){
//                $scan_rece_type=0;
//            }elseif(in_array(10, $body['pay_way'])){
//                $scan_rece_type=3;
//            }
//        }
        $pay_fee = ConfigChannel::instance()->getPayFee(['cid' => $cid]);
        $vipOrder['pay_rate']=$pay_fee;
        $extendsData = [
            'cd'                => $time,
            'cid'               => $cid,
            'mn_sid'            => $mn_sid,
            'giveup_money'      => $body['giveup_money'] ?? 0,
            'pay_way'           => isset($body['pay_way'])?implode(',', $body['pay_way']):0,
            'cash'              => $body['cash'] ?? 0,
            'scan_pay'          => $body['scan_pay'] ?? 0,
            'scan_rece'         => $body['scan_rece'] ?? 0,
            'scan_rece_type'    => $scan_rece_type,
            'pos'               => $body['pos'] ?? 0,
            'storecard'         => $body['storecard'] ?? 0,
            'storecard_id'      => $body['storecard_id'] ?? 0,
            'balance'           => $body['balance'] ?? 0,
            'coupon'            => $body['coupon'] ?? 0,
            'points'            => $body['points'] ?? 0,
            'cashregister_id'   => $cashregister_id,
            'casher'            => $manager_id
        ];
        Member::instance()->startTrans();
        try {
            if ($body['vip'] == 1){
                if ($body['is_pay'] ==1){
                    if(isset($body['scan_rece'])&&$body['scan_rece']>0){
                        $extra=[
                            'auth_code'=>$body['scan_code'],
                            'out_trade_no'=>$sn,
                            'body'=>'门店付款',
                            'total_fee'=>$body['scan_rece'],
                            'cid'=>$cid,
                            'mn_sid'=>$mn_sid,
                            'store_type'=>$mnuser['type'],
                            'buyer'=>$body['buyer']??[],
                            'order_id'=>'',
                            'scan_rece_type'=>$scan_rece_type,
                            'is_order'=>0,
                            'cash_register'     => $cash_register
                        ];
                        $user_pay_result = CashPayService::instance()->userPay($cid, $mn_sid,4, $extra);
                        if($user_pay_result['code'] == 200){
                            $vipOrder['pay_serial']=$user_pay_result['data']['transaction_id'];
                            $vipOrder['pay_time']=$time;
                            $vipOrder['is_online']=1;
                            $vip['type']=0;
//                            if($mnuser['type']==Mnuser::TYPE_STORE_QZ){
//                                $distribute_money=0;
//                                $vipOrder['is_online']=0;
//                            }else{
//                                $distribute_money=bcmul($body['scan_rece'], $pay_fee,2);
//                            }
//                            if($mnuser['type']!=Mnuser::TYPE_STORE_QZ){
//                                $budgete_extra=[
//                                    'type'       => MnBudgetService::TYPE_EXPENDITURE,
//                                    'money_type' => MnBudgetService::MONEY_TYPE_MEMBER,
//                                    'pay_type'   => 8,
//                                    'pay_serial' => $vipOrder['pay_serial'],
//                                    'sn'         => $sn,
//                                    'goods_id'   => 0,
//                                    'channel_money'      => $body['scan_rece'],
//                                    'channel_amount'     => 0,
//                                    'store_money'      => $distribute_money,
//                                    'store_amount'     => bcadd((string)$distribute_money, (string)$mnuser['wallet_income'], 2),
//                                    'remark'     => '购买会员卡收入',
//                                    'distribute_money'=>$distribute_money
//                                ];
//                                $mnbudget= MnBudgetService::instance()->addBudget($cid, $mn_sid, $mnuser['mid'], 4, $budgete_extra);
//                                if($mnbudget['code']!= Normal::SUC){
//                                    Member::instance()->rollback();
//                                    return $mnbudget;
//                                }
//                            }
                        }else{
                            Member::instance()->rollback();
                            return $user_pay_result;
                        }
                    }else{
                        $vipOrder['pay_serial']=Billcode::returnCode('', $mn_sid);
                        $vipOrder['pay_time']=$time;
                        $vipOrder['is_online']=1;
                        $vip['type']=0;
                    }
                } else {
                    $vipOrder ['type']=3;
                    $vipOrder ['is_online']=1;
                    $vip      ['type']=1;
                }
            }
            $accountres=Member::instance()->edit(['mid'=>$mid], ['edit_manager'=>$manager_name,'edit_time'=>$time]);
            if(!$accountres){
                Member::instance()->rollback();
                return Normal::returnCode(Normal::FAIL, '失败,会员');
            }
            if($body['vip']==1){
                $viplog=VipLog::instance()->add($vipOrder);    
                if(!$viplog){
                    Member::instance()->rollback();
                    return Normal::returnCode(Normal::FAIL, '失败,会员订单');
                }
                $extendsdata['vip_log_id']=$viplog;
                $orderextendsres= VipLogExtends::instance()->add($extendsdata);
                if(!$orderextendsres){
                    Member::instance()->rollback();
                    return Normal::returnCode(Normal::FAIL, '订单扩展新增失败');
                }
                $vipinfo= Vip::instance()->info(['mid'=>$mid]);
                if($vipinfo){
                    $memberinfo=Member::instance()->info(['mid'=>$mid]);
                    if($memberinfo['vip_expired']>$vipinfo['expire_time']){
                        $vipinfo['expire_time']=$memberinfo['vip_expired'];
                    }
                    $editvipinfodata=[];
                    if($vipinfo['expire_time']>$time){
                        $editvipinfodata['expire_time']=strtotime(date('Y-m-d',$vipinfo['expire_time']))+($day+1)*86400;
                    }else{
                        $editvipinfodata['expire_time']=strtotime(date('Y-m-d',$time))+($day+1)*86400;
                    }
                    $editvipinfodata['type']=$vip['type'];
                    $vipres=Vip::instance()->edit(['id'=>$vipinfo['id']],$editvipinfodata);
                    $membereditres=Member::instance()->edit(['mid'=>$mid],['vip_type'=>$vip['type'],'vip_level'=>1,'vip_expired'=>$editvipinfodata['expire_time']]);
                }else{
                    $vipres=Vip::instance()->add($vip);
                    $membereditres=Member::instance()->edit(['mid'=>$mid],['vip_type'=>$vip['type'],'vip_level'=>1,'vip_expired'=>$vip['expire_time']]);
                }
                if(!$vipres){
                    Member::instance()->rollback();
                    return Normal::returnCode(Normal::FAIL, '失败,会员记录');
                }
                if(!$membereditres){
                    Member::instance()->rollback();
                    return Normal::returnCode(Normal::FAIL, '失败,会员升级');
                }
            }
            Member::instance()->commit();
        }catch (\Exception $e){
            Member::instance()->rollback();
            return Normal::returnCode(Normal::FAIL, $e->getMessage());
        }


        return Normal::returnCode(Normal::SUC, '操作成功');
    }

    /**
     * 收银机确认购买人信息接口即用户认证
     * @param int $cid
     * @param int $mn_sid
     * @param array $body
     * @return array
     */
    public function memberAuth(int $cid,int $mn_sid,array $body = [])
    {
        if (empty($body['truename'])){
            return Normal::returnCode(Normal::FAIL,'真实姓名必传');
        }
        if (empty($body['mobile'])){
            return Normal::returnCode(Normal::FAIL, '手机号码必传');
        }
        if (empty($body['idcard'])) {
            return Normal::returnCode(Normal::FAIL, '身份证信息 必传');
        }
        //验证身份证
        $idcardauth = IdCardAuthService::instance()->checkIdCard([
                "true_name" => $body['truename'],
                "idcard"    => $body['idcard'],
                'cid'       => $cid]
        );
        if ($idcardauth['code'] != Normal::SUC) {
            return $idcardauth;
        }
        $body['sex'] = IdCardAuthService::instance()->get_sex($body['idcard']);
        $body['birthday'] = IdCardAuthService::instance()->get_birthday($body['idcard']);
        if(!isset($body['mid']) || empty($body['mid']) || $body['mid']<=0){
            $where  = [
                'df' => 0,
                'account' => $body['mobile']
            ];

            //添加条件
            $where[]=MnUserService::instance()->memberShareGetWhere($mn_sid);

            $member = Member::instance()->select([
                'mid','account','cd','points','vip_level'
            ])->where($where)->first();

            $mnuser= Mnuser::instance()->info(['id'=>$mn_sid]);

            if($member){
                /*
                 * 根据店铺配置判断是否是自动升级为黑卡会员
                 */
                if($mnuser['is_autovip']==1){
//                    $isvip= VipService::instance()->checkUserIsBlackVipCard($mnuser, [$member['mid']]);
//                    if($isvip[0]['is_vip']==0){
//                        VipService::instance()->addVipByCashAuto($member['mid'], $mn_sid);
//                    }
                    if($member['vip_level']==0){
                        VipService::instance()->addVipByCashAuto($member['mid'], $mn_sid);
                    }
                }
                return Normal::returnCode(Normal::FAIL, '该账号已存在，请先登录会员再修改订购信息！');
            }
            $res = $this->createAccount([
                'cid'      => $cid,
                'mn_sid'   => $mn_sid,
                'account'  => $body['mobile'],
                'password' => $body['mobile'], //原逻辑密码和账号一致
                'client'   => 'cash'
            ]);
            if ($res['code'] != Normal::SUC){
                return $res;
            }
            if($mnuser['is_autovip']==1){
                VipService::instance()->addVipByCashAuto($res['data'], $mn_sid);
            }
            $body['mid']=$res['data'];
            
            //兼容新版本收银机
            if( !empty($body['province']) && !empty($body['city']) && !empty($body['area']) && !empty($body['address']) ) {
                //添加默认收货地址
                Address::instance()
                ->add([
                    'mid'        => $body['mid'],
                    'true_name'  => $body['truename'],
                    'idcard'     => $body['idcard'],
                    'mobile'     => $body['mobile'],
                    'province'   => $body['province'],
                    'city'       => $body['city'],
                    'area'       => $body['area'],
                    'address'    => $body['address'],
                    'is_default' => 1,
                    'md'         => time(),
                    'cd'         => time(),
                ]);
            }
        }
        $editResult = MemberInfo::instance()->edit(
            ['mid'=>$body['mid']],
            [
                'truename'     => $body['truename'],
                'mobile'       => $body['mobile'],
                'idcard'       => $body['idcard'],
                'province'     => $body['province'] ?? 0,
                'city'         => $body['city'] ?? 0,
                'area'         => $body['area'] ?? 0,
                'address'      => $body['address'] ?? '',
                'sex'          => $body['sex'] ?? 0,
                'birthday'     => $body['birthday'] ?? '',
                'address_name' => $body['truename'],
            ]
        );
        return Normal::returnCode(Normal::SUC, '操作成功',[
            'mid'      => $body['mid'],
            'truename' => $body['truename'],
            'mobile'   => $body['mobile'],
            'idcard'   => $body['idcard'],
        ]);
    }
    
    /**
     * 创建账户(所有新增用户(后台添加、用户注册)都走这里创建) 非常重要
     * @param    array $param
     * @access   public
     * @return   array
     */
    public function createAccount(array $param = []):array{
        $res = MemberVolidate::instance()->validateCreate($param);
        if ($res['code'] != Normal::SUC) {
            return $res;
        }
        //用户账户
        $data  = [
            'account'    => $param['account'],
            'password'   => md5($param['password']),
            'cd'         => time(),
            'client'     => $param['client']??'wap',
            'mn_sid'     => $param['mn_sid']??0,
            'cid'        => $param['cid']??0,
        ];
        Member::instance()->startTrans();
        try {
            $res = Member::instance()->add($data);
            if (!empty($res)) {
                $info_data = [
                    'mid'       => $res, 
                    'nickname'  => !empty($param['nickname'])?$param['nickname']:StringService::hide_mobile($data['account']),
                    'avatar'  => $param['img']??'https://indoorbuy.oss-cn-hangzhou.aliyuncs.com/defaultweb/user/avatarUrl.png',
                ];
                if(!empty($param['guide_code'])){
                    $info = ShoppingGuide::instance()->info(['code'=>trim($param['guide_code']),'mn_sid'=>$param['mn_sid'],'cid'=>$param['cid'],'status'=>1]);
                    if(!empty($info)){
                        $info_data['guide_id']=$info['id'];
                        $info_data['guide_now']=$info['id'];
                        $info_data['guide_cd']=time();
                        $info_data['guide_md']=time();
                        MemberGuideLog::instance()->add(['mid'=>$res,'guide_id'=>$info['id'],'cd'=>time()]);
                    }
                }
                MemberInfo::instance()->add($info_data);
                //环信注册
                Member::instance()->commit();
                return Normal::returnCode(Normal::SUC,'创建成功',$res);
            }
        }catch (\Exception $e){
            Member::instance()->rollback();
            return Normal::returnCode(Normal::FAIL,$e->getMessage());
        }

    }
    
    /**
     * 根据购买人身份证检查上次购买时电话,并返回该号码的所属会员信息
     * @param int $cid
     * @param int $mn_sid
     * @param array $body
     * @return type
     */
    public function getMemberInfoByIdcard(int $cid,int $mn_sid,array $body = [])
    {
        if(empty($body['idcard'])){
            return Normal::returnCode(Normal::FAIL,'身份证不能为空');
        }
        $returnData=[
            'check'=>true,
            'member_info'=>[],
            'mobile'=>''
        ];
        $order= Order::instance()->info([
            'cid'           => $cid,
            'mn_sid'        => $mn_sid,
            'buyer_idcard'  => $body['idcard'],
            '_order_'       =>['cd'=>'desc']
        ]);
        if(empty($order)){
            $returnData['check']=false;
            return Normal::returnCode(Normal::SUC,'该身份证上次未购买',$returnData);
        }
        $buyer_mobile=$order['buyer_mobile'];
        $returnData['mobile']=$buyer_mobile;
        $member= $this->getMemberInfo($cid, $mn_sid, ['account'=>$buyer_mobile]);
        if($member['code']!=Normal::SUC){
            return Normal::returnCode(Normal::SUC,$member['msg'],$returnData);
        }
        $returnData['member_info']=$member['data'];
        return Normal::returnCode(Normal::SUC,'获取成功',$returnData);
    }
}
